<?php

namespace App\Models\Cashbook;

use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Relations\HasMany;

class CashbookModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = "cashbook";

    protected $fillable = [
        'id',
        'shopId',
        'userId',
        'recordTime',
        'type',
        'category',
        'source',
        'amount',
        'remark',
        'cycleId',
        'orderId',
        'isDeleted',
        'createdAt',
        'createdByUid',
        'updatedAt',
        'updatedByUid',
    ];

    const TYPE_INCOME = 1;
    const TYPE_PAY    = 2;

    const TYPE_TEXT_MAPPING = [
        self::TYPE_INCOME => '收入',
        self::TYPE_PAY    => '支出',
    ];

    const CATEGORY_1  = 1;
    const CATEGORY_2  = 2;
    const CATEGORY_3  = 3;
    const CATEGORY_4  = 4;
    const CATEGORY_5  = 5;
    const CATEGORY_6  = 6;
    const CATEGORY_7  = 7;
    const CATEGORY_8  = 8;
    const CATEGORY_9  = 9;
    const CATEGORY_10 = 10;
    const CATEGORY_11 = 11;
    const CATEGORY_12 = 12;
    const CATEGORY_13 = 13;
    const CATEGORY_14 = 14;
    const CATEGORY_15 = 15;
    const CATEGORY_16 = 16;
    const CATEGORY_17 = 17;

    const CATEGORY_TEXT_MAPPING_ALL = [
        self::CATEGORY_1  => '营业收入',
        self::CATEGORY_2  => '回收',
        self::CATEGORY_3  => '团餐预定',
        self::CATEGORY_4  => '其他',
        self::CATEGORY_5  => '订货',
        self::CATEGORY_6  => '水费',
        self::CATEGORY_7  => '电费',
        self::CATEGORY_8  => '房租',
        self::CATEGORY_9  => '员工工资',
        self::CATEGORY_10 => '网费',
        self::CATEGORY_11 => '采购',
        self::CATEGORY_12 => '退款',
        self::CATEGORY_13 => '返现',
        self::CATEGORY_15 => '推广',
        self::CATEGORY_14 => '其他',
        self::CATEGORY_16 => '买菜',
        self::CATEGORY_17 => '分销支出',
    ];

    //收入
    const CATEGORY_TEXT_MAPPING_INCOME = [
        self::CATEGORY_1 => '营业收入',
        self::CATEGORY_2 => '回收',
        self::CATEGORY_3 => '团餐预定',
        self::CATEGORY_4 => '其他',
    ];
    //支出
    const CATEGORY_TEXT_MAPPING_PAY = [
        self::CATEGORY_5  => '订货',
        self::CATEGORY_6  => '水费',
        self::CATEGORY_7  => '电费',
        self::CATEGORY_8  => '房租',
        self::CATEGORY_9  => '员工工资',
        self::CATEGORY_10 => '网费',
        self::CATEGORY_16 => '买菜',
        self::CATEGORY_11 => '采购',
        self::CATEGORY_12 => '退款',
        self::CATEGORY_13 => '返现',
        self::CATEGORY_15 => '推广',
        self::CATEGORY_17 => '分销支出',
        self::CATEGORY_14 => '其他',
    ];

    const SOURCE_SYSTEM_ADD      = 1;
    const SOURCE_ADD             = 2;
    const SOURCE_PERIOD_SYNC_ADD = 3;

    const SOURCE_TEXT_MAPPING = [
        self::SOURCE_SYSTEM_ADD      => '系统自动同步',
        self::SOURCE_ADD             => '手动添加',
        self::SOURCE_PERIOD_SYNC_ADD => '周期同步添加',
    ];

    const RMS_ORDERS_UPDATE_DATE         = 'rmsOrdersUpdate:date';//rms门店营业收入变更 存 日期 key
    const RMS_ORDERS_UPDATE_DATE_SHOP_ID = 'rmsOrdersUpdate:';    //rms门店营业收入变更 存 shopId key

    /**
     * 关联资源表
     * @return HasMany
     */
    public function resourcesRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId', 'id')
            ->where('module', ResourcesModel::MODULE_TYPE_CASHBOOK_ADD)
            ->where('business', ResourcesModel::BUSINESS_CASHBOOK_ADD)
            ->where('name', 'cashbookImg');
    }


    /**
     * 获取总金额
     * @param $shopId
     * @param string $userId
     * @param int $type
     * @param string $category
     * @param string $startTime
     * @param string $endTime
     * @param bool $isGroupDay
     */
    public static function getTotalAmount($shopId, $userId = '', $type = 0, $category = '', $startTime = '', $endTime = '', $isGroupDay = false)
    {
        $total = self::query()
            ->where('shopId', $shopId)
            ->when(
                $userId !== "" && is_array($userId), function ($query) use ($userId) {
                $query->whereIn('userId', $userId);
            }
            )
            ->when(
                $type, function ($query) use ($type) {
                $query->where('type', $type);
            }
            )
            ->when(
                $category && is_array($category), function ($query) use ($category) {
                $query->whereIn('category', $category);
            }
            )
            ->when(
                $startTime && $endTime, function ($query) use ($startTime, $endTime) {
                $query->whereBetween('recordTime', [strtotime($startTime), strtotime($endTime) + 86399]);
            }
            );

        if ($isGroupDay) {
            return $total->selectRaw("FROM_UNIXTIME(recordTime,'%Y-%m-%d') day,sum(amount) totalAmount")->groupBy('day')->get();
        } else {
            return $total->sum('amount');
        }
    }

    public static function insertData(array $data)
    {
        return self::query()->create($data);
    }

    public static function getInfoByOrderId($shopId, $orderIds)
    {
        return CashbookModel::query()
            ->where('shopId', $shopId)
            ->whereIn('orderId', $orderIds)
            ->get();
    }

    public static function getInfoByRecordTime($shopId, $recordTime, $category, $source)
    {
        return CashbookModel::query()
            ->where('shopId', $shopId)
            ->where('recordTime', $recordTime)
            ->where('category', $category)
            ->where('source', $source)
            ->first();
    }

    /**
     * 批量插入数据
     * @param array $data
     * @param int $count
     */
    public static function batchInsertData(array $data, $count = 500)
    {
        if (count($data) > $count) {
            foreach (array_chunk($data, $count) as $chunk) {
                self::query()->insert($chunk);
            }
        } else {
            self::query()->insert($data);
        }
    }
}
